<?php
/**
 * RegisterController.php
 *
 * @copyright  2023 beikeshop.com - All Rights Reserved
 * @link       https://beikeshop.com
 * @author     TL <mengwb@guangda.work>
 * @created    2023-04-20 20:22:54
 * @modified   2023-04-20 20:22:54
 */

namespace Beike\Seller\Http\Controllers;

use Beike\Admin\Repositories\PageRepo;
use Beike\Seller\Http\Requests\RegisterRequest;
use Beike\Seller\Models\SellerUser;
use Beike\Seller\Services\SellerService;
use function view;

class RegisterController extends Controller
{
    /**
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View
     */
    public function index()
    {
        $textAgree = '';
        if ($accountPageId = plugin_setting('multi_seller.account_page_id')) {
            if ($page = PageRepo::findByPageId($accountPageId)) {
                $textAgree = trans('seller::register.text_agree', ['page_url' => shop_route('pages.show', $accountPageId), 'page_name' => $page->description->title]);
            }
        }

        return view('seller::register', ['text_agree' => $textAgree]);
    }

    /**
     * @param RegisterRequest $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function store(RegisterRequest $request)
    {
        SellerService::register($request->only('email', 'store_name', 'password', 'type', 'id_card', 'id_number'));

        if (plugin_setting('multi_seller.approve_seller')) {
            return redirect(seller_route('login.index'))->with(['error' => trans('seller::login.success_unapproved')]);
        }

        $credentials = $request->only('email', 'password');
        auth(SellerUser::AUTH_GUARD)->attempt($credentials);

        return redirect(seller_route('home.index'));
    }
}
